package com.gf.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gf.base.type.Activity;
import com.gf.common.constant.Constants;
import com.gf.common.constant.ViewPaths;
import com.gf.common.util.ReloadUserInfoHelper;
import com.gf.common.util.SpringUtils;
import com.gf.user.model.User;
import com.gf.user.service.UserService;

/**
 * 对请求进行过滤 访问相关资源须进行登入
 * 
 * @author zhuguifeng
 * 
 */
public class CheckUserAuthorityFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected FilterConfig config;

	private Log logger = LogFactory.getLog(CheckUserAuthorityFilter.class);
	
	private UserService userService;

	@Override
	public void destroy() {
		config = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		userService = SpringUtils.getBean("userService");

		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();

		String method = req.getMethod();

		String url = getAllUrl(req);

		//监听每一个请求
		checkReload(session);
		
		User user = (User) session.getAttribute(Constants.SESSION_USER);
		//管理员在后台 冻结了某用户
		if(user!=null && user.getActivity()==Activity.FREEZED){
			session.removeAttribute(Constants.SESSION_USER);
			RequestDispatcher dispatcher;
			// 跳转到登入界面 登入后跳转到登入前的页面
			dispatcher = config.getServletContext()
					.getRequestDispatcher(
							ViewPaths.INFO_VIEW + ViewPaths.SUFFIX+"?info='Sorry,This account has been freezed!'");
			dispatcher.forward(request, response);
		}
		
		
		// 处理get请求 如果是post请求且用户没有登入，返回的数据由相应的controller控制
		if (user == null && method.equals("GET")) {
			// 帮助首页 :只有提问跟回复需要登入
			if (url.indexOf("base") != -1 || url.indexOf("getSuggestion") != -1
					|| (url.indexOf("help") != -1)) {
				chain.doFilter(request, response);
			}
			// 粉丝显示页面
			else if (url.indexOf("care.html") != -1
					|| url.indexOf("fans.html") != -1) {
				response.getWriter().write("UNLOGIN");
			}
			// 个人主页里"全网动态"，“我的发布等”都是先跳到页面，然后再加载数据
			else if (url.indexOf("event/news.html") != -1
					|| url.indexOf("event/news.html") != -1
					|| url.indexOf("event/myNews.html") != -1
					|| url.indexOf("event/myConcerned.html") != -1
					|| url.indexOf("exam/participateData.html") != -1
					|| url.indexOf("/exam/unReleasedOf.html") != -1
					|| url.indexOf("exam/releasedOfData.html") != -1) {
				response.getWriter().write("UNLOGIN");

			} else {
				logger.info("用户没有登入，跳转到登入界面:" + url);
				RequestDispatcher dispatcher;

				// 跳转到登入界面 登入后跳转到登入前的页面
				dispatcher = config.getServletContext()
						.getRequestDispatcher(
								ViewPaths.LOGIN_VIEW + ViewPaths.SUFFIX
										+ "?url=" + url);

				dispatcher.forward(request, response);
			}

		} // 用户已登入 或者 访问登入 注册页面 直接跳转
		else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}

	/**
	 * 得到完整的客户端请求的URL,包括参数
	 * 
	 * @param req
	 * @return
	 */
	private String getAllUrl(HttpServletRequest req) {
		String main = req.getRequestURL().toString();
		String paras = "";
		// 参数
		Enumeration<String> names = req.getParameterNames();
		List<String> namesList = new ArrayList<String>();
		while (names.hasMoreElements()) {
			namesList.add(names.nextElement());
		}
		if (namesList.size() == 0) {
			return main;
		}
		String first = namesList.get(0);
		paras += "?" + first + "=" + req.getParameterValues(first)[0];
		for (int i = 1; i < namesList.size(); i++) {
			String name = namesList.get(i);
			paras += "&" + name + "=" + req.getParameterValues(name)[0];
		}
		return main + paras;
	}
	
	
	
	/**
	 * 查看用户有没有必要重新从数据库中加载用户信息到session<br>
	 * 有的话自动加载，没有的话直接跳过
	 */
	private void checkReload(HttpSession session) {
		User user = (User) session.getAttribute(Constants.SESSION_USER);
		// 当前有用户登入
		if (user != null) {
			if (ReloadUserInfoHelper.getNeedReload(user.getId())) {
				logger.info("reload user info:"+user.getId()+" service:"+userService);
				User newUser = userService.getUserById(user.getId());
				
				session.setAttribute(Constants.SESSION_USER, newUser);
			}
		}
	}

}
